package com.hd.sup.modules.alarm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.hd.common.constant.BizConstant;
import com.hd.common.utils.*;
import com.hd.sup.modules.alarm.mapper.AlarmReportMapper;
import com.hd.sup.modules.alarm.model.AlarmReport;
import com.hd.sup.modules.alarm.service.IAlarmDailyStatisService;
import com.hd.sup.modules.alarm.service.IAlarmReportService;
import com.hd.sup.modules.alarm.util.AlarmUtils;
import com.hd.sup.modules.alarm.util.TemplateUtils;
import com.hd.sup.modules.district.model.Region;
import com.hd.sup.modules.district.service.IRegionService;
import com.hd.sup.modules.enterprise.model.Enterprise;
import com.hd.sup.modules.enterprise.service.IEnterpriseService;
import com.hd.sup.modules.vehicle.model.VehicleAlarmDailyStatis;
import com.hd.sup.modules.vehicle.service.IVehicleAlarmDailyStatisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报警报告表 服务实现类
 * </p>
 *
 * @author chentl123
 * @since 2020-12-28
 */
@Slf4j
@Service
public class AlarmReportServiceImpl extends ServiceImpl<AlarmReportMapper, AlarmReport> implements IAlarmReportService {

    public static final String REPORT_SUFFIX_DEFAULT = "道路运输监测平台分析报告";

    @Resource
    private IRegionService regionService;

    @Resource
    private IEnterpriseService enterpriseService;

    @Resource
    private IAlarmDailyStatisService alarmDailyStatisService;

    @Resource
    private IVehicleAlarmDailyStatisService vehicleAlarmDailyStatisService;

    @Resource
    private UserUtils userUtils;

    @Override
    public List<Map<String, Object>> pageList(Page<Map<String, Object>> page, AlarmReport alarmReport) {
        return this.baseMapper.pageList(page, alarmReport);
    }

    @Override
    public String generateBaseReportData(AlarmReport param) {
        StringBuilder reportName = new StringBuilder();
        String deptId = "";
        Pair<String, String> datePair = AlarmUtils.getStartEndDate(param.getDateStr(), param.getTimeFlag(), false);
        Date startDate = DateUtil.parseTime(datePair.first);
        Date endDate = DateUtil.parseTime(datePair.second);

        if (StringUtils.isNotBlank(param.getRegionCode())) {
            Region regionDb = regionService.getOne(new LambdaQueryWrapper<Region>().eq(Region::getCode, param.getRegionCode()));
            reportName.append(TemplateUtils.getReportNameRangeDesc(param.getTimeFlag())).append(regionDb.getName()).append("-").append(DateUtil.format(startDate, BizConstant.Common.DATE_FORMAT_DAY.key())).append("~").append(DateUtil.format(endDate, BizConstant.Common.DATE_FORMAT_DAY.key())).append(REPORT_SUFFIX_DEFAULT);
            deptId = regionDb.getDeptId();
        } else if (StringUtils.isNotBlank(param.getEnterpriseNo())) {
            Enterprise enterpriseDb = enterpriseService.getOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getEnterpriseNo, param.getEnterpriseNo()));
            reportName.append(TemplateUtils.getReportNameRangeDesc(param.getTimeFlag())).append(enterpriseDb.getName()).append("-").append(datePair.first).append("~").append(datePair.second).append(REPORT_SUFFIX_DEFAULT);
            deptId = enterpriseDb.getDeptId();
        }

        //组装数据
        String id = GenUtil.newId();
        param.setId(id);
        param.setStartDate(startDate);
        param.setEndDate(endDate);
        param.setGenerateStatus(BizConstant.GenerateStatus.GENERATING.key());
        param.setName(reportName.toString());
        param.setCreateBy(userUtils.currentUser().getUsername());
        param.setUpdateBy(userUtils.currentUser().getUsername());
        param.setDeptIds(JSON.toJSONString(userUtils.getDeptIdList()));
        param.setDeptId(deptId);

        param.insert();
        return id;
    }

    @Override
    public void updateReportData(String id, String reportJson) {
        AlarmReport alarmReportDb = getById(id);
        alarmReportDb.setReportJson(reportJson);
        alarmReportDb.setUpdateBy(userUtils.currentUser().getUsername());
        alarmReportDb.setVerifyTime(new Date());
        alarmReportDb.setVerifyBy(userUtils.currentUser().getUsername());
        alarmReportDb.setVerifyStatus(BizConstant.VerifyStatus.VERIFIED.key());

        alarmReportDb.updateById();
    }

    @Override
    public void fillReportData(String id) {
        AlarmReport alarmReportDb = getById(id);

        //取数据
        Map<String, Object> result = generateReportJson(alarmReportDb);

        alarmReportDb.setReportJson(MapUtils.isNotEmpty(result) ? JSON.toJSONString(result) : "");
        alarmReportDb.setGenerateStatus(BizConstant.GenerateStatus.GENERATED.key());

        alarmReportDb.updateById();
        log.info("[supervise] 分析报告: {} JSON数据已生成.", alarmReportDb.getName());

    }

    @Override
    public Map<String, Object> generateReportJson(AlarmReport alarmReport) {
        String dateStr = alarmReport.getDateStr();
        String enterpriseNo = alarmReport.getEnterpriseNo();
        String timeFlag = alarmReport.getTimeFlag();
        String regionCode = alarmReport.getRegionCode();
        List<String> deptIds = JSONArray.parseArray(alarmReport.getDeptIds(), String.class);


        Map<String, Object> result = Maps.newHashMap();
        Map<String, Object> report_data = Maps.newHashMap();
        VehicleAlarmDailyStatis param = VehicleAlarmDailyStatis.builder().dateStr(dateStr).regionCode(regionCode).enterpriseNo(enterpriseNo).timeFrame(AlarmUtils.getFrame(timeFlag)).build();

        //1 报警分布统计 + 环比 + 趋势 查询
        //今日
        Map<String, Object> today_alarm_data = todayOrYesterday(param, timeFlag, false);
        report_data.put("today", today_alarm_data);
        //昨日
        Map<String, Object> yesterday_alarm_data = todayOrYesterday(param, timeFlag, true);
        report_data.put("yesterday", yesterday_alarm_data);

        //2 企业处置率查询
        Map<String, Object> enterprise_handle_rate = alarmDailyStatisService.getWorstEnterpriseHandleRateTop20(param, timeFlag, deptIds);
        today_alarm_data.put("enterprise_handle_rate", enterprise_handle_rate);

        //3 总结模板结论
        String summary = TemplateUtils.getAlarmSummary(today_alarm_data, timeFlag);
        report_data.put("summary", summary);

        //封装数据
        result.put("report_data", report_data);
        return result;
    }

    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author chentl
     * @description 今日昨日查询 复用
     * @date 2021/2/20 2:32 下午
     * @params [param, pre]
     */
    private Map<String, Object> todayOrYesterday(VehicleAlarmDailyStatis param, String timeFlag, boolean pre) {
        Map<String, Object> alarm_data = Maps.newHashMap();
        //1 报警类型统计、报警趋势统计
        Map<String, Object> cur_all_alarm = vehicleAlarmDailyStatisService.generateAlarmReportData(param, timeFlag, pre);
        alarm_data.put("all_alarm", cur_all_alarm);

        int index = 1;
        for (BizConstant.VehicleTransType transType : BizConstant.VehicleTransType.values()) {
            if (transType.equals(BizConstant.VehicleTransType.OTHER) || transType.equals(BizConstant.VehicleTransType.FREIGHT))
                continue;
            index++;
            param.setTransType(transType.key());
            param.setParagraphs(index);
            Map<String, Object> cur_alarm = vehicleAlarmDailyStatisService.generateAlarmReportData(param, timeFlag, pre);
            alarm_data.put(transType.property() + "_alarm", cur_alarm);
        }
        return alarm_data;
    }
}
